<?php
namespace App\Http\Controllers\Business\Admin\Auth;

use App\Http\Controllers\Business\Shop\V1\Admin\Admin;
use App\Models\AdminRole;
use App\Models\AdminUser;
use App\Models\City;
use App\Models\SmsMessage;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;

class AdminAuth
{
    //登录
    public static function adminLogin($mobile,$password) {
        if (!$mobile || !$password) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $user = AdminUser::where(array('mobile' => $mobile, 'password' => md5($password . env('PASSWORD_SALT')), 'status' => '1'))->first();
        if ($user) {
            $user->logintime = date('Y-m-d H:i:s',time());
            $user->save();
            return ['status' => 'success', 'data' => array('userid' => $user['id'])];
        } else {
            return ['status' => 'failed', 'message' => '手机号或密码错误！'];
        }
    }
    //重置密码
    public static function resetPassword($mobile,$code,$newpassword) {
        if (!$mobile || !$code || !$newpassword) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        if (!SmsMessage::loginIdentifyingCodeVerify($mobile,$code,'3')) {
            return ['status' => 'failed', 'message' => '验证码错误！'];
        }
        $user = AdminUser::where('mobile', $mobile)->first();
        $user->password = md5($newpassword . env('PASSWORD_SALT'));
        $user->save();
        return ['status' => 'success', 'message'=>'修改成功'];
    }
    //获取验证码
    public static function getCode($mobile) {
        if(!$mobile) {
            return ['status'=>'failed','message'=>'请求数据不完整！'];
        }
        if (SmsMessage::loginIdentifyingCode($mobile,'3')) {
            return ['status'=>'success','message'=>'短信发送成功！'];
        }else {
            return ['status'=>'failed','message'=>'短信发送失败，请稍后再试！'];
        }
    }
    //编辑密码
    public static function editPassword($oldpassword,$newpassword) {
        if (!$oldpassword || !$newpassword) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $user = AdminUser::find(Auth::guard('adminweb')->id());
        if ($user) {
            if (md5($oldpassword . env('PASSWORD_SALT')) == $user['password']) {
                $user->password = md5($newpassword . env('PASSWORD_SALT'));
                $user->save();
                return ['status' => 'success', 'message'=>'修改成功！'];
            } else {
                return ['status' => 'failed', 'message' => '旧密码错误！'];
            }
        }
    }
    //个人信息
    public static function myUserInfo() {
        $user = AdminUser::where('id',Auth::guard('adminweb')->id())->select('mobile','realname', 'cityauth', 'rolename', 'auth')->first();
        $cityauth = $user['cityauth'];
        $cityauth = json_decode($cityauth, true);
        $cityNameArray = [];
        foreach($cityauth as $key => $value) {
            $cityName = City::where('id', $key)->pluck('name')->first();
            if($cityName) {
                if(!in_array($cityName, $cityNameArray)) {
                    array_push($cityNameArray, $cityName);
                }
            }
        }
        $user['cityauth'] = $cityNameArray;
        $user['auth'] = self::getAdminAuth($user['auth']);
        if ($user) {
            return ['status' => 'success', 'data' => $user];
        } else {
            return ['status' => 'failed', 'message'=>'获取信息失败'];
        }
    }
    //通过用户id,获取用户名称和手机号码
    public static function getUserNameAndMobileByUserId($userid) {
        $data = AdminUser::where('id', $userid)->select('mobile','realname')->first();
        return ['status'=>'success', 'data'=>$data];
    }
    //管理员用户列表
    public static function adminUserList($cityid, $roleid, $perpage='50') {
        if(!$cityid) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        if($roleid == 1 || $roleid ==2 || $roleid==3) {
            //全国管理员
            $userlist = AdminUser::orWhere('cityid', $cityid)
                ->orWhere('cityid', 'like', '%,' . $cityid . ',%')
                ->orWhere('cityid', 'like', $cityid . ',%')
                ->orWhere('cityid', 'like', '%,' . $cityid)
                ->where(function ($query) {
                    foreach ($GLOBALS['Districtid'] as $v) {
                        $query->orWhere('districtid', $v)
                            ->orWhere('districtid', 'like', '%,' . $v . ',%')
                            ->orWhere('districtid', 'like', $v . ',%')
                            ->orWhere('districtid', 'like', '%,' . $v);
                    }
                })->select('id', 'mobile', 'realname', 'roleid', 'rolename', 'created_at', 'status')
                ->orderBy('created_at', 'desc')->orderBy('status', 'asc')->paginate($perpage);
        } else {
            //代理商管理员
            $GLOBALS['cityid'] = $cityid;
            $userlist = AdminUser::where('roleid', '<>', 1)
                ->where('roleid', '<>', 2)
                ->where('roleid', '<>', 3)
                ->where('roleid', '<>', 5)
                ->where(function($query) {
                    $query->orWhere('cityid', $GLOBALS['cityid'])
                        ->orWhere('cityid', 'like', '%,' . $GLOBALS['cityid'] . ',%')
                        ->orWhere('cityid', 'like', $GLOBALS['cityid'] . ',%')
                        ->orWhere('cityid', 'like', '%,' . $GLOBALS['cityid']);
                })
                ->where(function ($query) {
                    foreach ($GLOBALS['Districtid'] as $v) {
                        $query->orWhere('districtid', $v)
                            ->orWhere('districtid', 'like', '%,' . $v . ',%')
                            ->orWhere('districtid', 'like', $v . ',%')
                            ->orWhere('districtid', 'like', '%,' . $v);
                    }
                })->select('id', 'mobile', 'realname', 'roleid', 'rolename', 'created_at', 'status')
                ->orderBy('created_at', 'desc')->orderBy('status', 'asc')->paginate($perpage);
        }
        return ['status' => 'success', 'data' => $userlist];
    }
    //通过城市id获取所有的代理商商务人员
    public static function getBusinessPeopleList($cityid) {
        if(!$cityid ) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $GLOBALS['cityid'] = $cityid;

        if($cityid == 1) {
            //南昌分公司的王肖宇也添加进去
            $data = AdminUser::where('status', 1)
                ->where(function($query) {
                    $query->orwhere('roleid', 13)->orwhere('id', 30);
                })
                ->Where(function($query){
                    $query->orWhere('cityid', $GLOBALS['cityid'])
                        ->orWhere('cityid','like', '%,'. $GLOBALS['cityid'] .',%')
                        ->orWhere('cityid','like', $GLOBALS['cityid'].',%')
                        ->orWhere('cityid','like', '%,'.$GLOBALS['cityid']);
                })->get();
        } else {
            $data = AdminUser::where('roleid', 13)->where('status', 1)->Where(function($query){
                $query->orWhere('cityid', $GLOBALS['cityid'])
                    ->orWhere('cityid','like', '%,'. $GLOBALS['cityid'] .',%')
                    ->orWhere('cityid','like', $GLOBALS['cityid'].',%')
                    ->orWhere('cityid','like', '%,'.$GLOBALS['cityid']);
            })->get();
        }
        return ['status'=>'success', 'data'=>$data];
    }
    //通过roleid获取可以所管辖的角色
    public static function getSubRoleListByRoleId($roleId) {
        if(!$roleId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if($roleId == 1) {
            //超级管理员
            //$data = AdminRole::where('id', '>', 1)->select('id as roleid', 'rolename')->get();
            $data = AdminRole::select('id as roleid', 'rolename')->get(); //TODO
        } elseif($roleId == 2) {
            //管理员
            $data = AdminRole::where('id', '>', 2)->select('id as roleid', 'rolename')->get();
        } elseif($roleId == 4) {
            //代理商
            $data = AdminRole::where('id', '>', 4)->where('rolename', 'like', '%代理商%')->select('id as roleid', 'rolename')->get();
        } else {
            return ['status'=>'failed', 'message'=>'你没有权限访问'];
        }
        return ['status'=>'success', 'data'=>$data ];
    }
    //通过roleid和cityid获取可以选择的城市
    public static function getCityListByRoleIdAndCityId($roleId, $cityId) {
        if(!$roleId || !$cityId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if(($roleId == 1) || ($roleId == 2)) {
            //超级管理员, 管理员
            $data = City::where('status', '1')->select('id as cityid', 'name')->get();
        } elseif($roleId == 4) {
            //代理商
            $data = City::where('status', '1')->where('id', $cityId)->select('id as cityid', 'name')->get();
        } else {
            return ['status'=>'failed', 'message'=>'你没有权限'];
        }
        return ['status'=>'success', 'data'=>$data ];
    }
    //新增管理用户
    public static function addAdminUser($mobile,$password,$realname,$roleid,$isalldata,$status,$cityauth,$note,$cityid,$districtid)
    {
        if(!$mobile||!$password||!$realname||!$roleid||!$cityauth) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $userinfo = AdminUser::where('mobile',$mobile)->orWhere('realname',$realname)->first();
        if($userinfo || !preg_match("/^1[34578]{1}\d{9}$/",$mobile)) {
            return ['status' => 'failed', 'message' => '手机号或姓名重复！'];
        } else {
            if($roleid == '4') {
                //代理商不能同一个城市和同一个区县
                $count = AdminUser::where('cityid', $cityid)->get()->count();
                if($count > 0) {
                    return ['status' => 'failed', 'message' => '该城市已开通了代理商'];
                }
            }
            $user = new AdminUser();
            $user->mobile = $mobile;
            $user->password = md5($password . env('PASSWORD_SALT'));
            $user->realname=$realname;
            $user->roleid = $roleid;
            $user->isalldata = $isalldata;
            $user->status = $status;
            $user->cityauth = $cityauth;
            $user->note = $note;
            $user->cityid = $cityid;
            $user->districtid = $districtid;
            $user->rolename = AdminRole::where('id',$roleid)->pluck('rolename')->first();
            $user->auth = AdminRole::where('id',$roleid)->pluck('auth')->first();
            $user->adminid = Auth::guard('adminweb')->id();
            $user->save();
            return ['status' => 'success', 'message'=>'添加成功'];
        }
    }
    //获取管理用户
    public static function getAdminUser($userId) {
        if (!$userId) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $userinfo = AdminUser::where('id',$userId)->select('id as userid', 'mobile', 'realname', 'roleid', 'isalldata', 'status', 'cityauth', 'cityid', 'districtid', 'note')->first();
        return ['status' => 'success', 'data' => $userinfo];
    }
    //禁用，或者恢复用户
    public static function updateAdminUserStatus($roleId, $accountId, $status) {
        if(!$roleId||!$accountId) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $account = AdminUser::where('id', $accountId)->first();
        if(!$account) {
            return ['status'=>'failed', 'message'=>'获取信息失败'];
        }
        if($roleId == 1) {
            //超级管理员
            if($account->roleid == 1) {
                return ['status'=>'failed', 'message'=>'权限不够'];
            }
        } elseif($roleId == 2) {
            if($account->roleid == 1 || $account->roleid == 2) {
                return ['status'=>'failed', 'message'=>'权限不够'];
            }
        } elseif($roleId == 4) {
            if($account->roleid <= 4) {
                return ['status'=>'failed', 'message'=>'权限不够'];
            }
        } else {
            return ['status'=>'failed', 'message'=>'权限不够'];
        }
        $account->status = $status;
        $account->save();
        return ['status'=>'success', 'message'=>'修改成功'];
    }
    //更新管理用户
    public static function updateAdminUser($userid,$realname, $roleid,$isalldata,$status,$cityauth,$note, $resigntime=''){
        if (!$userid || !$roleid || !$realname) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $loginuser = Auth::guard('adminweb')->user();
        $loginuserroleid = $loginuser->roleid;
        if($loginuserroleid == 1) {
            //超级管理员
            if($roleid == 1) {
                //return ['status' => 'failed', 'message' => '权限不够'];
            }
        } elseif($loginuserroleid == 2) {
            //管理员
            if($roleid==1 || $roleid ==2) {
                return ['status' => 'failed', 'message' => '权限不够'];
            }
        } elseif($loginuserroleid == 4) {
            //代理商
            if($roleid<=4) {
                return ['status' => 'failed', 'message' => '权限不够'];
            }
        }
        $districtId = '';
        $cityId = '';
        $cityArray = json_decode($cityauth, true);
        foreach($cityArray as $key=>$value) {
            if($cityId) {
                $cityId .= ',' . $key;
            } else {
                $cityId = $key;
            }
            foreach($value as $list) {
                if ($districtId) {
                    $districtId .= ',' . $list;
                } else {
                    $districtId .= $list;
                }
            }
        }
        $user = AdminUser::where('id',$userid)->first();
        $user->realname = $realname;
        $user->roleid = $roleid;
        $user->isalldata = $isalldata;
        $user->status = $status;
        $user->cityauth = $cityauth;
        $user->cityid = $cityId;
        $user->districtid = $districtId;
        $user->note = $note;
        $user->rolename = AdminRole::where('id',$roleid)->pluck('rolename')->first();
        $user->auth = AdminRole::where('id',$roleid)->pluck('auth')->first();
        $user->adminid = Auth::guard('adminweb')->id();
        if($resigntime) {
            $user->deserttime = $resigntime;
        }
        $user->save();
        Redis::del('Admin:CityAuth:'.$userid);
        Redis::del('Admin:Auth:'.$userid);
        return ['status' => 'success', 'message'=>'添加成功！'];
    }
    //更新手机号码
    public static function updateMobile($adminUserId,$oldMobile,$newMobile) {
        if (!$adminUserId || !$oldMobile || !$newMobile || !preg_match("/^1[34578]{1}\d{9}$/",$newMobile)) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $adminUserAuth = AdminUser::where('id', $adminUserId)->pluck('auth')->first();
        if(!$adminUserAuth) {
            return ['status' => 'failed', 'message' => '获取信息失败！'];
        }
        $auth = json_decode($adminUserAuth, true);
        //adminUserManagement:edit
        if(!in_array("adminUserManagement:edit", $auth)) {
            return ['status'=>'failed', 'message'=>'权限不够'];
        }
        $userInfo = AdminUser::where('mobile',$oldMobile)->first();
        if($userInfo) {
            $userInfo->mobile = $newMobile;
            $userInfo->save();
            return ['status' => 'success', 'message'=>'修改成功'];
        } else {
            return ['status' => 'failed', 'message'=>'修改失败'];
        }
    }
    //更新密码
    public static function updatePassword($userid,$newpassword) {
        if (!$userid || !$newpassword) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $userinfo = AdminUser::find($userid);
        if($userinfo)
        {
            $userinfo->password = md5($newpassword . env('PASSWORD_SALT'));
            $userinfo->save();
            return ['status' => 'success', 'message'=>'修改成功'];
        }
        return ['status' => 'failed', 'message'=>'修改失败'];
    }
    //通过用户密码更新密码
    public static function updatePasswordByOldPassword($userId, $oldPassword, $newPassword) {
        if (!$userId || !$newPassword || !$oldPassword) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $userinfo = AdminUser::where('id', $userId)->where('password', md5($oldPassword . env('PASSWORD_SALT')))->first();
        if($userinfo) {
            $userinfo->password = md5($newPassword . env('PASSWORD_SALT'));
            $userinfo->save();
            return ['status' => 'success', 'message'=>'修改成功'];
        } else {
            return ['status' => 'failed', 'message'=>'修改错误'];
        }
    }
    //角色列表
    public static function adminRoleList() {
        return ['status' => 'success', 'data' => AdminRole::select('id as roleid','rolename','created_at')->get()];
    }
    //新增角色
    public static function addAdminRole($rolename,$auth) {
        if (!$rolename || !$auth) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $count = AdminRole::where('rolename', $rolename)->get()->count();
        if($count > 0) {
            return ['status' => 'failed', 'message' => '该角色已添加了'];
        }
        $role = new AdminRole();
        $role->rolename = $rolename;
        $role->auth = $auth;
        $role->adminid = Auth::guard('adminweb')->id();
        $role->save();
        return ['status' => 'success', 'message'=>'新增角色成功'];
    }
    //更新角色
    public static function updateAdminRole($roleid,$rolename = '',$auth = '') {
        if (!$roleid || !$rolename) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $role = AdminRole::find($roleid);
        if($role) {
            $role->rolename = $rolename;
            $role->auth = $auth;
            $role->adminid = Auth::guard('adminweb')->id();
            $role->save();
            return ['status' => 'success', 'message'=>'更改信息成功'];
        }
    }
    //通过roleid 获取角色信息
    public static function getRoleInfoByRoleId($roleId) {
        if(!$roleId) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $adminRole = AdminRole::where('id', $roleId)->first();
        if($adminRole) {
            $data = [
                'roleid' => $roleId,
                'auth' => $adminRole['auth'],
                'name' => $adminRole['rolename'],
            ];
            return ['status'=>'success', 'data'=>$data];
        }
        return ['status'=>'failed', 'message'=>'获取失败'];
    }
    //获取用户权限
    public static function getAdminAuth($auth='') {
        $adminauth = self::getAllAuth();
        if ($auth) {
            $auth = json_decode($auth, true);
            $newauth = [];
            foreach ($auth as $value) {
                foreach ($adminauth as $k => $v) {
                    foreach ($adminauth[$k] as $k1 => $v1) {
                        if (array_key_exists($value, $v1)) {
                            if (!array_key_exists($k, $newauth)) {
                                if (!$newauth) {
                                    $newauth = array($k => '');
                                } else {
                                    $newauth = array_merge($newauth, array($k => ''));
                                }
                            }
                            if (!$newauth[$k]) {
                                if (!$newauth[$k]) {
                                    $newauth[$k] = array($k1 => '');
                                } else {
                                    $newauth[$k] = array_merge($newauth[$k], array($k1 => ''));
                                }
                            } else {
                                if (!array_key_exists($k1, $newauth[$k])) {
                                    if (!$newauth[$k]) {
                                        $newauth[$k] = array($k1 => '');
                                    } else {
                                        $newauth[$k] = array_merge($newauth[$k], array($k1 => ''));
                                    }
                                }
                            }
                            if (!$newauth[$k][$k1]) {
                                $newauth[$k][$k1] = array($value => $v1[$value]);
                            } else {
                                $newauth[$k][$k1] = array_merge($newauth[$k][$k1], array($value => $v1[$value]));
                            }
                        }
                    }
                }
            }
            return $newauth;
        } else {
            return $adminauth;
        }
    }
    //所有的权限列表
    public static function getAllAuth() {
        return array(
            '短信验证码查询' =>
                array(
                    '短信验证码查询' =>
                        array(
                            'smsSelect' => '查看',
                        ),
                ),
            '后台用户管理' =>
                array(
                    '后台账号列表' =>
                        array(
                            'adminUserManagement' => '查看',
                            'adminUserManagement:add' => '新增',
                            'adminUserManagement:edit' => '修改',
                            'adminUserManagement:del' => '删除',
                            'adminUserManagement:export' => '导出',
                        ),
                    '角色管理' =>
                        array(
                            'adminRoleManagement' => '查看',
                            'adminRoleManagement:add' => '新增',
                            'adminRoleManagement:edit' => '修改',
                            'adminRoleManagement:del' => '删除',
                        ),
                    '代理商管理' =>
                        array(
                            'adminRoleManagement' => '查看',
                            'adminRoleManagement:add' => '新增',
                            'adminRoleManagement:edit' => '修改',
                            'adminRoleManagement:del' => '删除',
                        ),
                ),
            '系统管理' =>
                array(
                    '地区管理' =>
                        array(
                            'areaManagement' => '查看',
                            'areaManagement:add' => '新增',
                            'areaManagement:edit' => '修改',
                            'areaManagement:del' => '删除',
                        ),
                    '分类管理' =>
                        array(
                            'classManagement' => '查看',
                        ),
                    '积分规则' =>
                        array(
                            'pointManagement' => '查看',
                        ),
                    '用户协议' =>
                        array(
                            'userAgreement' => '查看',
                        ),
                    '商家协议' =>
                        array(
                            'shopAgreement' => '查看',
                        ),
                    'app版本' =>
                        array(
                            'appVersion' => '查看',
                            'appVersion:edit' => '修改',
                        ),
                    '红包设置' =>
                        array(
                            'redEnvelope' => '查看',
                            'redEnvelope:edit' => '编辑',
                        ),
                ),
            '用户版运营' =>
                array(
                    '用户列表' =>
                        array(
                            'userManagement' => '查看',
                            'userManagement:edit' => '修改',
                            'userManagement:export' => '导出',
                        ),
                    '地区用户' =>
                        array(
                            'userRegion' => '查看',
                            'userRegion:edit' => '修改',
                        ),
                    'Banner列表' =>
                        array(
                            'bannerManagement' => '查看',
                            'bannerManagement:add' => '新增',
                            'bannerManagement:edit' => '修改',
                            'bannerManagement:del' => '删除',
                        ),
                    '启动页列表' =>
                        array(
                            'appStartManagement' => '查看',
                            'appStartManagement:add' => '新增',
                            'appStartManagement:edit' => '修改',
                            'appStartManagement:del' => '删除',
                        ),
                    '热搜管理' =>
                        array(
                            'searchManagement' => '查看',
                            'searchManagement:add' => '新增',
                            'searchManagement:edit' => '修改',
                            'searchManagement:del' => '删除',
                        ),
                    '红包管理' =>
                        array(
                            'userRedEnvelope' => '查看',
                            'userRedEnvelope:edit' => '修改',
                        ),
                    '用户帮助中心' =>
                        array(
                            'userHelpManagement' => '查看',
                        ),
                    '用户消息管理' =>
                        array(
                            'userMessageManagement' => '查看',
                            'userMessageManagement:add' => '新增',
                        ),
                    '用户反馈管理' =>
                        array(
                            'userFeedbackManagement' => '查看',
                            'userFeedbackManagement:edit' => '修改',
                        ),
                ),
            '商家版运营' =>
                array(
                    '已上架商家列表' =>
                        array(
                            'shopManagement' => '查看',
                            'shopManagement:add' => '新增',
                            'shopManagement:edit' => '修改',
                            'shopManagement:del' => '删除',
                        ),
                    '审核不通过列表' =>
                        array(
                            'staffVerifyManagement' => '查看',
                            'staffVerifyManagement:edit' => '修改',
                            'staffVerifyManagement:del' => '删除',
                        ),
                    '待审核商家列表' =>
                        array(
                            'verifyManagement' => '查看',
                            'verifyManagement:edit' => '修改',
                        ),
                    '已下架商家管理' =>
                        array(
                            'banShopManagement' => '查看',
                            'banShopManagement:edit' => '修改',
                            'banShopManagement:del' => '删除',
                        ),
                    '商家状态记录' =>
                        array(
                            'shopStatus' => '查看',
                            'shopStatus:export' => '导出'
                        ),
                    '翻倍日管理' =>
                        array(
                            'doubleDayManagement' => '查看',
                            'doubleDayManagement:edit' => '修改',
                            'doubleDayManagement:export' => '导出',
                        ),
                    '夜场管理' =>
                        array(
                            'nightShopManagement' => '查看',
                            'nightShopManagement:edit' => '修改',
                        ),
                    '商家帮助中心' =>
                        array(
                            'shopHelpManagement' => '查看',
                        ),
                    '商家消息管理' =>
                        array(
                            'shopMessageManagement' => '查看',
                            'shopMessageManagement:add' => '新增',
                        ),
                    '商家反馈管理' =>
                        array(
                            'shopFeedbackManagement' => '查看',
                            'shopFeedbackManagement:edit' => '修改',
                        ),
                ),
            '订单管理' =>
                array(
                    '充值订单列表' =>
                        array(
                            'rechargeManagement' => '查看',
                            'rechargeManagement:edit' => '修改',
                            'rechargeManagement:export' => '导出',
                        ),
                    '消费订单列表' =>
                        array(
                            'orderManagement' => '查看',
                            'orderManagement:export' => '导出',
                        ),
                    '用户退款记录' =>
                        array(
                            'refundManagement' => '查看',
                        ),
                    '全部评价列表' =>
                        array(
                            'commentManagement' => '查看',
                            'commentManagement:del' => '删除',
                        ),
                    '举报评价列表' =>
                        array(
                            'reportManagement' => '查看',
                            'reportManagement:edit' => '修改',
                        ),
                    '商家回评列表' =>
                        array(
                            'shopCommentManagement' => '查看',
                            'shopCommentManagement:del' => '删除',
                        ),
                ),
            '财务中心' =>
                array(
                    '平台资金流水' =>
                        array(
                            'ledgerAccount' => '查看',
                            'ledgerAccount:add' => '新增',//后台充值
                        ),
                    '用户对账单' =>
                        array(
                            'userStatement' => '查看',
                            'userStatement:export' => '导出',
                        ),
                    '商家对账单' =>
                        array(
                            'shopStatement' => '查看',
                            'shopStatement:export' => '导出',
                        ),
                    '商家待提现列表' =>
                        array(
                            'waitWithdraw' => '查看',
                            'waitWithdraw:export' => '导出',
                        ),
                    '商家已提现列表' =>
                        array(
                            'alreadyWithdraw' => '查看',
                            'alreadyWithdraw:export' => '导出',
                        ),
                    '商务月账单' =>
                        array(
                            'commission' => '查看',
                            'commission:export' => '导出',
                        ),
                    '地推对帐单' =>
                        array(
                            'shopSalesmanStatement' => '查看',
                            'shopSalesmanStatement:export' => '导出',
                        ),
                    '地推已提现' =>
                        array(
                            'shopSalesmanWithdrawal' => '查看',
                            'shopSalesmanWithdrawal:export' => '导出',
                        ),
                    '地推待提现' =>
                        array(
                            'shopSalesmanWaitWithdrawal' => '查看',
                            'shopSalesmanWaitWithdrawal:export' => '导出',
                        ),
                    '代理商分润' =>
                        array(
                            'agentProfit' => '查看',
                        ),
                    '代理商对账单' =>
                        array(
                            'agentStatement' => '查看',
                        ),
                    '代理商待提现' =>
                        array(
                            'agentWaitWithdrawal' => '查看',
                            'agentWaitWithdrawal:edit' => '修改',
                            'agentWaitWithdrawal:export' => '导出',
                        ),
                    '代理商已提现' =>
                        array(
                            'agentWithdrawal' => '查看',
                            'agentWithdrawal:export' => '导出'
                        ),
                    '代理收款账号管理' =>
                        array(
                            'agentReceivableManage' => '查看',
                            'agentReceivableManage:edit' => '修改'
                        ),
                ),
            '地推管理' =>
                array(
                    '商家地推列表' =>
                        array(
                            'shopSalesmanManagement' => '查看',
                            'shopSalesmanManagement:add' => '新增',
                            'shopSalesmanManagement:edit'=> '修改',
                            'shopSalesmanManagement:del' => '删除',
                            'shopSalesmanManagement:export'=> '导出',
                        ),
                    '个人地推列表' =>
                        array(
                            'userSalesmanManagement' => '查看',
                            'userSalesmanManagement:edit' => '修改'
                        ),
                    '地推设置' =>
                        array(
                            'salesmanSetManagement' => '查看',
                            'salesmanSetManagement:edit' => '编辑'
                        ),
                ),
            '数据报表' =>
                array(
                    '统计概况' =>
                        array(
                            'statistical' => '查看',
                        ),
                ),
        );
    }
    //刷新角色权限
    public static function refreshAdminRoleAuthByRoleName($roleName) {
        if(!$roleName) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        $roleId = AdminRole::where('rolename', $roleName)->pluck('id')->first();
        if(!$roleId) {
            return ['status'=>'failed', 'message'=>'刷新角色失败'];
        }
        $adminUsers = AdminUser::where('roleid', $roleId)->get();
        foreach($adminUsers as $v) {
            AdminUser::where('id',$v['id'])->where('status', '1')->update(['auth'=>AdminRole::where('id',$v['roleid'])->pluck('auth')->first()]);
            Redis::del('Admin:Auth:'.$v['id']);
            Redis::del('Admin:CityAuth:'.$v['id']);
        }
        return ['status'=>'success', 'message'=>'刷新成功'];
    }
    //刷新权限
    public static function refreshAdminUserAuth($adminuserid='') {
        if($adminuserid) {
            //刷新单个用户
            $adminuser = AdminUser::where('id', $adminuserid)->where('status', '1')->first();
            if($adminuser) {
                $roleid = $adminuser->roleid;
                $adminuser->auth = AdminRole::where('id',$roleid)->pluck('auth')->first();
                Redis::del('Admin:Auth:'.$adminuserid);
                Redis::del('Admin:CityAuth:'.$adminuserid);
                $adminuser->save();
            }
        } else {
            //刷新全部用户
            $adminuser = AdminUser::get();
            foreach ($adminuser as $v) {
                AdminUser::where('id',$v['id'])->where('status', '1')->update(['auth'=>AdminRole::where('id',$v['roleid'])->pluck('auth')->first()]);
                Redis::del('Admin:Auth:'.$v['id']);
                Redis::del('Admin:CityAuth:'.$v['id']);
            }
        }
        return ['status'=>'success', 'message'=>'刷新成功'];
    }
    //判断用户是否具备某个权限
    public static function isHasThisAuthByAdminUserId($adminUserId, $auth) {
        if(!$adminUserId || !$auth) {
            return false;
        }
        $authJson = AdminUser::where('id', $adminUserId)->pluck('auth')->first();
        if(!$authJson) {
            return false;
        }
        $authArray = json_decode($authJson, true);
        if(!is_array($authArray)) {
            return false;
        }
        if(in_array($auth, $authArray)) {
            return true;
        } else {
            return false;
        }
    }
    //代理商列表
    public static function agentList() {
        $data = AdminUser::where('admin_users.roleid', 4)
            ->join('city', 'admin_users.cityid', '=', 'city.id')
            ->select('admin_users.id', 'admin_users.mobile', 'admin_users.realname', 'city.name as cityname', 'admin_users.status', 'admin_users.created_at')
            ->get();
        return ['status'=>'success', 'data'=>$data];
    }
    //新增代理商
    public static function addAgent($mobile,$password,$realName,$status,$cityAuth,$note,$cityId,$districtId,$cardHolder='', $bankCard='',$bankName='', $bankProvince='',$bankCity='',$openCardBank='') {
        if(!$mobile||!$password||!$realName||!$cityAuth) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $userinfo = AdminUser::where('mobile',$mobile)->orWhere('realname',$realName)->first();
        if($userinfo || !preg_match("/^1[34578]{1}\d{9}$/",$mobile)) {
            return ['status' => 'failed', 'message' => '手机号或姓名重复！'];
        } else {
            //代理商不能同一个城市和同一个区县
            $count = AdminUser::where('cityid', $cityId)->where('roleid', 4)->get()->count();
            if($count > 0) {
                return ['status' => 'failed', 'message' => '该城市已开通了代理商'];
            }
            $user = new AdminUser();
            $user->mobile = $mobile;
            $user->password = md5($password . env('PASSWORD_SALT'));
            $user->realname=$realName;
            $user->roleid = 4;
            $user->isalldata = 1;
            $user->status = $status;
            $user->cityauth = $cityAuth;
            $user->note = $note;
            $user->cityid = $cityId;
            $user->districtid = $districtId;
            $user->rolename = AdminRole::where('id',4)->pluck('rolename')->first();
            $user->auth = AdminRole::where('id',4)->pluck('auth')->first();
            $user->cardholder = $cardHolder;
            $user->bankname = $bankName;
            $user->bankcard = $bankCard;
            $user->opencardbank = $openCardBank;
            $user->bankprovince = $bankProvince;
            $user->bankcity = $bankCity;
            $user->adminid = Auth::guard('adminweb')->id();
            $user->save();
            return ['status' => 'success', 'message'=>'添加成功'];
        }
    }
    //获取代理商详情
    public static function getAgent($adminUserId) {
        if (!$adminUserId) {
            return ['status' => 'failed', 'message' => '请求数据不完整！'];
        }
        $userinfo = AdminUser::where('id',$adminUserId)->select('id as userid', 'mobile', 'realname', 'roleid', 'isalldata', 'status', 'cityauth', 'cityid', 'districtid', 'note')->first();
        return ['status' => 'success', 'data' => $userinfo];
    }
    //编辑代理商
    public static function editAgent() {

    }
    //删除代理商
    public static function deleteAgent($adminUserId) {

    }
}